package com.dingding.javabasic.Juc.CAS;



import sun.misc.Unsafe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Solution {

    public volatile int i = 0;
    public void cas() throws Exception {
        Class<Unsafe> unsafeClass = Unsafe.class;
        Constructor<Unsafe> declaredConstructor = unsafeClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Unsafe unsafe = declaredConstructor.newInstance();

        Field field = Solution.class.getDeclaredField("i");
        field.setAccessible(true);

        final long VALUE = unsafe.objectFieldOffset(field);
        ExecutorService executor = Executors.newFixedThreadPool(40);
        for(int a=0; a<5; a++) {
            Runnable run = () -> {
                for (int j = 0; j < 100; j++) {
                    System.out.println("线程" + Thread.currentThread().getId() + "正在执行");
                    do {

                    } while (!unsafe.compareAndSwapInt(this, VALUE, i, i+1));
                }
            };
            executor.execute(run);
        }
        Thread.sleep(30000);
        System.out.println(i);
    }



}
